package game_logic.control.listener;

import game_logic.Controller;
import game_logic.model.Board;
import game_logic.util.Utils;
import connect.Client;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.Objects;

/**
 * 监听者，监听用户输入、网络信息。前者来自于用户鼠标点击，后者来自对手的操作
 */
public class Listener extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
        if (currentPlayer % 2 != owner) return; // 没到自己动
        if (e.getButton() != MouseEvent.BUTTON1) return; // 只处理左击
        int viewX = e.getX(), viewY = e.getY(); // 获得点击坐标
        int[] modelPos = Utils.getModelPos(new int[]{viewX, viewY}, reverseBoard);
        positions.addLast(modelPos[0]);
        positions.addLast(modelPos[1]);
        controller.gameViewUpdate();
        if (positions.size() < 4) return; // 说明现在是开始坐标，跳过
        // 取出坐标
        int sx = positions.pollFirst(), sy = positions.pollFirst(), tx = positions.pollFirst(), ty = positions.pollFirst();
        // 尝试移动
        if (!controller.move(sx, sy, tx, ty)) return; // 如果移动失败，那么结束
        // 移动成功了
        if (!Objects.equals(targetIP, "")) {
            // 通信
            try {
                this.client.sendMessage(targetIP, String.format("%d %d %d %d", sx, sy, tx, ty));
            } catch (Exception ex) {
                System.out.println("发送信息失败");
                throw new RuntimeException(ex);
            }
            currentPlayer += 1;
        }

        if (this.board.isGameOver()) {
            // Client.release();
            Thread.interrupted();
        }

    }

    public int[] getFirstPos() {
        if (positions.isEmpty()) return null;
        return new int[]{positions.get(0), positions.get(1)};
    }


    /**
     * 构造函数，传入是否反转棋盘
     *
     * @param reverseBoard 是否反转棋盘
     */
    public Listener(boolean reverseBoard, Client client, int owner) {
        this.client = client;
        this.reverseBoard = reverseBoard;
        this.owner = owner;
        this.currentPlayer = 0; // 红方先
    }

    /**
     * 绑定游戏控制器、对手 IP 地址
     *
     * @param controller 游戏控制器
     * @param targetIP   对手 IP 地址
     */
    public void bind(Controller controller, String targetIP, Board board) {
        this.controller = controller;
        this.targetIP = targetIP;
        this.board = board;
    }

    private Board board;
    private Controller controller; // 游戏控制器
    private String targetIP; // 对方 ip
    private final boolean reverseBoard; // 显示棋盘时，是否反转
    private final int owner; // 玩家 id
    public int currentPlayer; // 当前出手的玩家 id
    public Client client; // 连接对面用户


    private final LinkedList<Integer> positions = new LinkedList<>();
}

